#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Zhangcl
import json, os, subprocess
from web import models
from django import conf


class MultiTaskManger(object):
    '''负责解析并触发批量任务'''

    def __init__(self, request):
        self.request = request

        self.call_task()

    def task_parser(self):
        '''解析任务'''

        self.task_data = json.loads(self.request.POST.get('task_data'))

    def call_task(self):
        self.task_parser()

        if self.task_data['task_type'] == 0:  # cmd
            self.cmd_task()

        elif self.task_data['task_type'] == 1:  # file_upload
            self.file_transfer_task()

    def cmd_task(self):
        task_obj = models.Task.objects.create(user=self.request.user,
                                              task_type=self.task_data['task_type'],
                                              content=self.task_data['cmd'])

        sub_task_obj = []

        for host_id in self.task_data['selected_host_ids']:
            sub_task_obj.append(models.TaskLogDetail(task=task_obj, bind_host_id=host_id, result='init....', status=2))

        models.TaskLogDetail.objects.bulk_create(sub_task_obj)

        task_script_obj = subprocess.Popen("python %s %s" % (conf.settings.MULTITASK_SCRIPT, task_obj.id),
                                           shell=True,
                                           stdout=subprocess.PIPE)

        self.task = task_obj

    def file_transfer_task(self):
        task_obj = models.Task.objects.create(user=self.request.user,
                                              task_type=self.task_data['task_type'],
                                              content=self.task_data['remote_path'])
        sub_task_obj = []

        for host_id in self.task_data['selected_host_ids']:
            sub_task_obj.append(
                models.TaskLogDetail(task=task_obj, bind_host_id=host_id, result='send file ing....', status=2))

        models.TaskLogDetail.objects.bulk_create(sub_task_obj)
        username = str(self.request.user)
        local_file = "%s/%s.zip" % (conf.settings.TMP_FILE_UPLOAD_DIR, username)
        file_name = "%s.zip" % username
        host_file = os.path.join(self.task_data['remote_path'], file_name)
        print(host_file, local_file)
        task_script_obj = subprocess.Popen(
            "python %s %s %s %s %s" % (
            conf.settings.MULTITASK_SCRIPT_SEND_FILE, task_obj.id, local_file, host_file, str(self.request.user)),
            shell=True,
            stdout=subprocess.PIPE)

        self.task = task_obj
